package com.example.demo2.common.config.security;


import com.example.demo2.common.config.security.fitler.WebSecurityTokenFilter;
import com.example.demo2.common.config.security.handler.AuthenticationEntryPointHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConfig {

    public static final String[] notFilterUrl = {"/doc.html","/webjars/**","/img.icons/**","/swagger-resources/**","/**","/v2/api-docs"};

    public static final String[] loginUrl = {"/user/login"};

    public static final String[] staticResource = {"/webjars/"};


    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Autowired
    public WebSecurityTokenFilter webSecurityTokenFilter;

    @Autowired
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                //关闭crsf
                .csrf().disable()
                .cors()
                .and()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //允许登陆接口匿名访问
                .antMatchers(loginUrl).anonymous()
                .antMatchers(notFilterUrl).permitAll()
                //以下请求全部需要认证
                .anyRequest().authenticated();

        http.addFilterBefore(webSecurityTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointHandler);
        return http.build();
    }
}
